//
//  LaunchViewController.swift
//  ManBetX
//
//  Created by Cocoa on 2020/3/23.
//  Copyright © 2020 Fullen. All rights reserved.
//

import UIKit
import Lottie

// 启动页
let automateTime = 3.0//页面停留时间，超过时间，自动跳转
class LaunchViewController: UIViewController {
    
// MARK: -- property

    @IBOutlet var jumpButton: UIButton!
    @IBOutlet var bgImageView: UIImageView!
    var currentViewController: UIViewController?
    var isSet : Bool = false  //是否设置了domain
    var isJumpToTabbarController : Bool = false//是否已经跳转至tabbarController
    
    var isStatusBarHidden = false {
        didSet{
            self.setNeedsStatusBarAppearanceUpdate()
        }
    }
    
    override var prefersStatusBarHidden: Bool {
        return self.isStatusBarHidden
    }
    
// MARK: -- Func
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        self.bgImageView.isHidden = false
        self.isStatusBarHidden=true
        self.jumpButton.isHidden = true
        
        configureUI()
        addNotifation()
        
//        AppDataConfigure.fetchAppchannel()
        
        
    }
    
    // 获取 - 配置 - 数据
    func fetchData() {
        AppDataConfigure.requestEagleeyes()
        AppDataConfigure.configureGameJson {
            //配置 gameJson完成
            self.setStatus()
        }
        AppDataConfigure.getGameJsonData()
        AppDataConfigure.getDoMainIp {}
        AppDataConfigure.getSignKey(succeedBlock: {
            //获取 signKey成功后才出现跳过按钮
            DispatchQueue.main.async {
                self.configureJumpButton()
            }
        }, failedBlock: {
            //获取 signKey 失败
            DispatchQueue.main.async {
                self.showAlertAction()
            }
        })
                    
//        AppDataConfigure.newCheckLocation2 {
//            // 如果IP被限制访问，则不再执行enterTabBarViewController
//            self.isJumpToTabbarController = true
//            self.switchFobiddenView()
//        }
    }
    
    // 添加网络监控通知
    func addNotifation() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.netWorkUsable),name: Notification.Name(NotifationKey.netWorkUsable.rawValue),object: nil)

        NotificationCenter.default.addObserver(self, selector: #selector(self.netWorkDisabled),name: Notification.Name(NotifationKey.netWorkDisabled.rawValue),object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NotifationKey.netWorkUsable.rawValue), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NotifationKey.netWorkDisabled.rawValue), object: nil)
    }
    // 网络状态 - 可用
    @objc func netWorkUsable(note: NSNotification){
        print("网络状态 - 可用")
        DispatchQueue.main.async {
            self.fetchData()
        }
    }
    // 网络状态 - 不可用
    @objc func netWorkDisabled(note: NSNotification){
        print("网络状态 - 不可用")
    }
    
    func configureUI(){
        if isIphone6 {
            self.bgImageView.image = UIImage.init(named: "750x1334")
        }else if isIphone6P {
            self.bgImageView.image = UIImage.init(named: "1242x2208")
        }else if isIphoneX {
            self.bgImageView.image = UIImage.init(named: "1125x2436")
        }else if isIphoneXR {
            self.bgImageView.image = UIImage.init(named: "828x1792")
        }else if isIphoneXS_Max {
            self.bgImageView.image = UIImage.init(named: "1242x2688")
        }
    }
    // 配置按钮及3秒自动跳过
    func configureJumpButton() {
        self.jumpButton.isHidden = false
        DispatchQueue.main.asyncAfter(deadline: .now() + automateTime) {
            // automateTime 时间后 确定为用户已经进入APP
            self.jumpButtonClick(self.jumpButton)
        }
    }
    // 获取 signKey 失败，禁止下一步
    func showAlertAction(){
        let alert = UIAlertController.init(title: "提示", message: "获取关键数据失败，请您重启软件重试", preferredStyle: .alert)
        let close = UIAlertAction.init(title: "关闭", style: UIAlertAction.Style.default) { (click) in
            exit(0)
        }
        alert.addAction(close)
        self.present(alert, animated: true, completion: nil)
    }
    
   // 检测是不是第一次启动，然后做一些配置
    func setStatus(){
        
//        let iconAnimationView = AnimationView.init(name: "hud_load2")
//        iconAnimationView.play()
        
        let isNotFirstLaunch = UserDefaults.standard.bool(forKey: DefaultKey.APP_NOTFIRST_LAUNCH)
        
        if isNotFirstLaunch {// 不是第一次启动
            let data = UserDefaults.standard.data(forKey: DefaultKey.LOGIN_DATA)
            if(data != nil){// 获取之前登陆的数据
                let json = JSON.init(data!)
                setData(responseData: json)
                let dict =  json["data"].dictionaryValue
                performEnterMainPageRequest2True(withLogin: true, dict: dict)
            }else {
                // 没有登陆数据
            }
        }else {// 第一次启动 - 设置引导页
            //            self.switchGuideView()
        }
    }
    
    func setData(responseData:JSON){
        DispatchQueue.main.async {
            let dict =  responseData["data"].dictionaryValue
            let c = dict["c"]?.intValue ?? -1
            let m = dict["m"]?.stringValue ?? ""
            if c == 0 {
               let tokenDict = dict["resultLogin"]?.dictionaryObject
                let infoDict = dict["resultGetMemberInfo"]?.dictionaryObject
                GlobalInfo.memberInfoData = infoDict
                let ccToken =  tokenDict?["cc"] as? String ?? ""
                let vcToken =  tokenDict?["vc"] as? String ?? ""
                let defaults = UserDefaults.standard
                if(isTest){
                    defaults.set(vcToken, forKey: DefaultKey.VCTOKEN81)
                    defaults.set(ccToken, forKey: DefaultKey.CCTOKEN81)
                }else{
                    defaults.set(vcToken, forKey: DefaultKey.VCTOKEN11)
                    defaults.set(ccToken, forKey: DefaultKey.CCTOKEN11)
                }
                RequestHelper.makeCFCookie()
                RequestHelper.addTokenCookies()
                RequestHelper.makeGameDomainCookie()
                
                UserHelper.setLoginStatus(true)
                self.performEnterMainPageRequest2True(withLogin: true, dict: dict)

            }else if (c == 1007) {
                  UIHelper.alertSimpleMessage(about: "登录失败", withDescription: m, in: self)
            }
        }
    }
    
    func switchGuideView(){
        currentViewController?.removeFromParent()
        self.bgImageView.isHidden = true
        let vc = GuideViewController.instanceFromStoryboard()!
        
        vc.didMove(toParent: self)

        self.addChild(vc)
        
        self.view.addSubview(vc.view)
        self.currentViewController = vc
        
    }
    
    func performEnterMainPageRequest2True(withLogin: Bool = false,dict: [String : JSON]){
        print("已异步获取到gamejson")
        let maintainData: [String:String]? = nil
        let platforms = GlobalInfo.gameInfoData?["platforms"] as? [[String:Any]] ?? [[String:Any]]()
        if GlobalInfo.isMaintain() == true{// 系统维护
            if withLogin {
                DispatchQueue.main.async {
                    UIHelper.alertIsMainTain(about:"系统维护",withDescription:GlobalInfo.gameInfoData?["maintain_msg"] as! String,urlString:GlobalInfo.gameInfoData?["maintain_cs_url"] as! String)
                }
            }
            
            return
        }
        DispatchQueue.main.async {
         let responseDict = dict["resultGetGameStatus"]?.dictionaryValue
          let responseDataDict =  responseDict?["response"]?.dictionaryValue
          let hallArr = responseDataDict?["data"]?.arrayObject  as? [[String : Any]] ?? [[String : Any]]()
            let memberinfoDict = dict["resultGetMemberInfo"]?.dictionaryObject
            let resultGetInfoDict = dict["resultGetInfo"]?.dictionaryValue
            let resultGetInfoDataDict = resultGetInfoDict?["response"]?.dictionaryObject ?? [String : Any]()
            
            GlobalInfo.memberInfoData = memberinfoDict
            GlobalInfo.siteInfoData = resultGetInfoDataDict
            GlobalInfo.platformInfoData = platforms
            
            GlobalInfo.hallInfoData = hallArr
            GlobalInfo.gameMaintainData = maintainData
        }
    }
    
    func switchFobiddenView(){
        UserDefaults.standard.set(nil, forKey: DefaultKey.USER_IS_AUTO_LOGIN)
        self.currentViewController?.removeFromParent()

        let vc: WebViewController = WebViewController.init()
         let url = "https://" + UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! + "/home/forbidden"
        vc.url = url
        vc.navigationBarExist = false
        UIApplication.shared.keyWindow?.rootViewController = vc
    }
    
    @IBAction func jumpButtonClick(_ sender: UIButton) {
        // 点击
        if self.isJumpToTabbarController == false {
            self.isJumpToTabbarController = true
             // 1 有引导页 跳转引导页？
            let isNotFirstLaunch = UserDefaults.standard.bool(forKey: DefaultKey.APP_NOTFIRST_LAUNCH)
                   
            if isNotFirstLaunch { //不是第一次启动没有引导页:跳转TabBarViewController
                enterTabBarViewController()
            }else {// 第一次启动 - 设置引导页
                self.switchGuideView()
               
            }
        }
    }
    
    // 跳转TabBarViewController
    func enterTabBarViewController() {
        
        let tabBarViewController = TabBarViewController.instanceFromStoryboard()!
        if #available(iOS 13.0, *) {
        
            UIApplication.shared.windows.first?.rootViewController = tabBarViewController
        }else {
            UIApplication.shared.keyWindow?.rootViewController = tabBarViewController
        }
    }
}
